import React, { useState, useEffect } from 'react';
import {connect} from 'dva';
import { Button, Drawer, Spin, Modal } from 'antd';
import Cron from 'cron-editor-react';
import SeeCronNextDate from "@/pages/common/cron/SeeCronNextDate";

const { confirm } = Modal;


/**
 * 编辑定时任务
 * @param props
 * @param ref
 * @returns {*}
 * @constructor
 */
function EditCron(props,ref) {
  const [ visible, setVisible ] = useState(false);
  const { dispatch, loading, cron, jobName } = props;
  const [value, setValue] = useState('* * * * * ?');

  useEffect(() => {
    setValue(cron);
  },[cron])

  // 初始化
  const preInit = () => {
    setVisible(true);
  }

  // 提交
  const onsubmit = () => {
    // 更改了结果，做更新
    confirm({
      title: '确定要更新Cron表达式吗?',
      onOk() {
        // update schedule
        if (dispatch) {
          dispatch({
            type: 'quartz/updateSchedule',
            params: {
              jobName: jobName,
              cron: value
            }
          }).then(res => {
            if (res){
              setVisible(false)
            }
          })
        }
      },
    });
  }

  return (
    <span>
      <Button type="link" onClick={preInit}>{value}</Button>
      <Drawer
        title="定时任务详情"
        placement="right"
        closable={false}
        onClose={() => setVisible(false)}
        visible={visible}
        width={650}
      >
        <Spin spinning={loading}>
          <Cron showCrontab value={value} onChange={val => setValue(val)} />
          <SeeCronNextDate key={value} value={value} />
        </Spin>
        {/* 操作 */}
        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={() => setVisible(false)} style={{ marginRight: 8 }}>
            Cancel
          </Button>
          <Button onClick={onsubmit} type="primary">
            Submit
          </Button>
        </div>
      </Drawer>
    </span>
  )
}


export default connect(({quartz, loading}) => ({
  loading: loading.models.quartz,
}))(EditCron);
